package com.zhmsky.filter;

import com.zhmsky.config.shiro.JwtToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @description preHandle->isAccessAllowed->isLoginAttempt->executeLogin
 * @author zhmsky
 * @date 2021/12/5 16:31
 */
public class JwtFilter extends BasicHttpAuthenticationFilter {

    /**
     * @param request
     * @param response
     * @param mappedValue
     * @return
     * @description 如果带有token，则对token进行检查，否则直接通过
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //判断请求的请求头中是否带有“Token”
        if (isLoginAttempt(request, response)) {
            //如果存在token，则进入executeLogin方法执行登入，检查token是否有效
            try {
                executeLogin(request, response);
                return true;
            } catch (Exception e) {
                //token验证失败
                responseError(response, e.getMessage());
            }
        }
        //如果请求头中没有携带Token，那么直接放行(可能是在执行登录操作或者游客模式访问，此时无需检查Token)
        return true;
    }

    /**
     * @param request
     * @param response
     * @return
     * @description 判断用户是否想要登入, 检查请求头中是否携带Token
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("Token");
        return token != null;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("Token");
        JwtToken jwtToken = new JwtToken(token);
        //提交给realm进行登入,如果错误会抛出异常
        getSubject(request, response).login(jwtToken);
        //如果没有抛出异常则登入成功
        return true;
    }

    /**
     * @description 对跨域提供支持
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * @param response
     * @param message
     * @description 将非法请求重定向到 /unauthorized/**
     */
    private void responseError(ServletResponse response, String message) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        try {
            //为了避免中文字符在重定向时乱码
            message = URLEncoder.encode(message, "UTF-8");
            //将非法请求重定向到 /unauthorized/**
            httpServletResponse.sendRedirect("/unauthorized/" + message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
